package com.ftg.learnmybatis.annotation.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.ftg.learnmybatis.Student;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.TypeAliasRegistry;

/**
 * 通用mybatis配置文件,完成对mybatis配置功能
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/3/14 下午3:50
 */
public class BaseMybatisUtil {

    /**
     * 缓存
     */
    public static SqlSession session;

    static{

        Configuration config = new Configuration();
        //没有相关的配置
        TransactionFactory tf = new JdbcTransactionFactory();

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:10086/homework");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");

        Environment env = new Environment("mysql",tf,dataSource);
        //看sql的日志
        config.setLogImpl(StdOutImpl.class);
        config.setEnvironment(env);

//        config.getTypeAliasRegistry().registerAliases("com.ftg.learn.mapper");

       XMLMapperBuilder xml;

//        XMLMapperBuilder xml = new XMLMapperBuilder(BaseMybatisUtil.class.getResourceAsStream("/config/student.xml"),config,"/config/student.xml",config.getSqlFragments());
//        xml.parse();

        config.addMappers("com.ftg.learnmybatis.annotation.mapper");

        SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();

        SqlSessionFactory ssf = ssfb.build(config);

        session = ssf.openSession(true);
    }

    /**
     * 返回session
     * @return
     */
    public static SqlSession getSession(){
        return session;
    }

    /**
     * 返回session里面的某一个接口的实现类
     * @param target  接口
     * @return
     * @param <T>
     */
    public static <T> T getInterfaceInSession(Class<T> target){
        return session.getMapper(target);
    }

}
